/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing_class;

import gui.JSlidePlotter;
import gui.Spaning;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import stendcontrol.CoefConfigurator;
import stendcontrol.Configurator;
import stendcontrol.DBServer;
import stendcontrol.DataProcessor;
import stendcontrol.Experiment;
import stendcontrol.ExperimentContainer;
import stendcontrol.FileServer;
import stendcontrol.MessageBuilder;
import stendcontrol.Param;
import stendcontrol.SensorInformer;
import stendcontrol.StendControlAPI;
import stendcontrol.UdpImplementer;
import stendcontrol.UdpServer;

/**
 *
 * @author minaev
 */
public class Experiment_Test extends javax.swing.JFrame {

    ExperimentContainer exp_cont = new ExperimentContainer();
    UdpServer udp_serv;
    UdpImplementer udpImpl;
    Configurator cnf = Configurator.getConf();

    /**
     * Creates new form Experiment_Test
     */
    public Experiment_Test() throws Exception {
        initComponents();
        udp_serv = new UdpServer("127.0.0.255",
                (Integer) cnf.getProperty(Configurator.UDP_IN_PORT),
                (Integer) cnf.getProperty(Configurator.UDP_OUT_PORT));
        udpImpl = new UdpImplementer(udp_serv);
        this.setLocationRelativeTo(null);
        // System.setErr(null);  

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        pan = new org.math.plot.Plot2DPanel();
        span1 = new gui.JSlidePlotter();
        span2 = new gui.JSlidePlotter();
        span3 = new gui.JSlidePlotter();
        jBtnViewer = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        toBase = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        loadDB = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Test");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout span1Layout = new javax.swing.GroupLayout(span1);
        span1.setLayout(span1Layout);
        span1Layout.setHorizontalGroup(
            span1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 199, Short.MAX_VALUE)
        );
        span1Layout.setVerticalGroup(
            span1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 138, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout span2Layout = new javax.swing.GroupLayout(span2);
        span2.setLayout(span2Layout);
        span2Layout.setHorizontalGroup(
            span2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 201, Short.MAX_VALUE)
        );
        span2Layout.setVerticalGroup(
            span2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout span3Layout = new javax.swing.GroupLayout(span3);
        span3.setLayout(span3Layout);
        span3Layout.setHorizontalGroup(
            span3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        span3Layout.setVerticalGroup(
            span3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jBtnViewer.setText("Viewer");
        jBtnViewer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnViewerActionPerformed(evt);
            }
        });

        jButton2.setText("Load");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        toBase.setText("savToBase");
        toBase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toBaseActionPerformed(evt);
            }
        });

        jButton3.setText("toFS");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        loadDB.setText("loadFromBase");
        loadDB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadDBActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pan, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBtnViewer)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addGap(18, 18, 18)
                .addComponent(toBase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addGap(18, 18, 18)
                .addComponent(loadDB)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(span1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(span2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(span3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(span1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(span2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(span3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pan, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jBtnViewer)
                    .addComponent(jButton2)
                    .addComponent(toBase)
                    .addComponent(jButton3)
                    .addComponent(loadDB)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            //udp_serv.removeAllListeners();

            UDP_Fluder udp_flud = new UDP_Fluder("127.0.0.255", 1);

            MessageBuilder mb = new MessageBuilder();
            DataProcessor dp = new DataProcessor();
            Experiment exp = new Experiment();
            final SensorInformer si = new SensorInformer(
                    CoefConfigurator.getConf().getSensorCoef0(),
                    CoefConfigurator.getConf().getSensorCoefProp());

            StendControlAPI sc = new StendControlAPI(udpImpl, si);
            sc.setSensorType(false);
            sc.setSampleInterval(1);
            sc.setResearchType(StendControlAPI.TYPE_RESEARCH_TIME);
            Thread t_udp_flud = new Thread(udp_flud);
            Thread t_udp_serv = new Thread(udp_serv);
            Thread t_mb = new Thread(mb);

            JSlidePlotter sps[] = {span1, span2, span3};
            int indx_sps[] = {0, 1, 2};
            Spaning span = new Spaning(si, sps, indx_sps);
            Thread t_span = new Thread(span);

            udp_serv.addTransmitListener(mb);
            udp_serv.addTransmitListener(si);
            mb.addMessageListener(exp);
            exp.open();

            t_mb.start();


            udp_serv.startTransmitToExp();
            t_udp_serv.start();

            t_udp_flud.start();

            t_span.start();

            Thread.sleep(10000);

            span.stopSpan();
            udp_flud.shutdown();
            udp_serv.stopUDPThread();
            mb.stopBuilding();

            System.out.println("span wait...");
            t_span.join();
            System.out.println("flud wait...");
            t_udp_flud.join();
            System.out.println("serv wait...");
            // t_udp_serv.join();
            System.out.println("mb wait...");
            t_mb.join();



            exp.close();

            while (!exp.isClosed()) {
            }


            /*
             MeasureSeqMessage msm = exp.getFirstMeasureSeq();
             int k = 0;
            
            
             while (msm != null) {
             System.out.println("MeasSeq size:" + msm.getSize());
             /*for (int i = 0; i < msm.getSize(); i++) {
             System.out.println("sensor val:"+msm.getSensorValue(0, i)+":"+proc0[k]);
             k++;
             }*//*
             msm = msm.getNextMeasureSeq();
             }
             */
            /*pan.addLinePlot(null, Color.RED, exp.getProcess(0));
             pan.addLinePlot(null, Color.GREEN, exp.getProcess(1));
             pan.addLinePlot(null, Color.BLUE, exp.getProcess(2));*/

            System.out.println("gen");
            exp.updateDataSensors();
            exp.getPositions();
            for (int i = 0; i < Configurator.COUNT_SENSOR; i++) {
                dp.setProcess(exp.getProcess(i), exp.getPositions());
                exp.addParam(new Param("M", Param.P_MEAN, dp.getMean()),
                        i);
            }
            System.out.println("end gen");

            exp.setExpName("Experiment" + exp_cont.getSize());

            exp_cont.addExp(exp);




            cnf.saveConfig();

            udp_serv.removeAllListeners();
        } catch (Exception ex) {
            Logger.getLogger(Experiment_Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jBtnViewerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnViewerActionPerformed
        /*ExperimentTreeModel etm = new ExperimentTreeModel(exp_cont);
         ViewerFrame vf = new ViewerFrame(etm);
         vf.setVisible(true);*/
        ViewerExperimentsModel_Test vemt = new ViewerExperimentsModel_Test(exp_cont);
        vemt.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        vemt.pack();
        vemt.setVisible(true);
    }//GEN-LAST:event_jBtnViewerActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        FileServer fs = new FileServer();
        //  JFileChooser fc = new JFileChooser();
        fs.chooseCurrentDirectory();
//        fs.setCurrentDirectory(fc.getSelectedFile().getAbsolutePath());
        int len = fs.getNamesExp().length;
        for (int i = 0; i < len; i++) {
            Experiment exp = fs.loadExp(i);
            exp_cont.addExp(exp);
            exp.updateDataSensors();
            for (int j = 0; j < Configurator.COUNT_SENSOR; j++) {
                exp_cont.getExp(exp_cont.getSize() - 1).getProcess(j);

            }
            exp_cont.getExp(exp_cont.getSize() - 1).getPositions();


        }

        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void toBaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toBaseActionPerformed
    }//GEN-LAST:event_toBaseActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        FileServer fs = new FileServer();
        fs.chooseCurrentDirectory();
        fs.saveExp(exp_cont.getExp(exp_cont.getSize() - 1));

        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void loadDBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadDBActionPerformed

     
    }//GEN-LAST:event_loadDBActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Experiment_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Experiment_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Experiment_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Experiment_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {

                    Experiment_Test et = new Experiment_Test();
                    et.setVisible(true);
                    // et.addMouseListener(ms);
                } catch (Exception ex) {
                    Logger.getLogger(Experiment_Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    /*static MouseListener ms = new MouseListener() {

     @Override
     public void mouseClicked(MouseEvent e) {
     System.out.println("Mouse clicked");
     if (e.isPopupTrigger()) System.out.println("Popup works!");
     }

     @Override
     public void mousePressed(MouseEvent e) {
     System.out.println("Mouse pressed");
     }

     @Override
     public void mouseReleased(MouseEvent e) {
          
     }

     @Override
     public void mouseEntered(MouseEvent e) {
        
     }

     @Override
     public void mouseExited(MouseEvent e) {
           
     }
    
     };  */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnViewer;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton loadDB;
    private org.math.plot.Plot2DPanel pan;
    private gui.JSlidePlotter span1;
    private gui.JSlidePlotter span2;
    private gui.JSlidePlotter span3;
    private javax.swing.JButton toBase;
    // End of variables declaration//GEN-END:variables
}
